package com.cuixichang.minimalism.acl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cuixichang.minimalism.basal.base.Validate;
import com.cuixichang.minimalism.basal.enums.IsEnableEnum;
import com.cuixichang.minimalism.basal.enums.SubassemblyTypeEnum;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

@Component
public class CheckboxSubassemblyDesign extends SubassemblyDesignAbs{
    @Override
    public SubassemblyTypeEnum getType() {
        return SubassemblyTypeEnum.Checkbox;
    }

    @Override
    public String example() {
        return "{\"Code\":\"Check\",···}";
    }

    @Override
    public Validate structureValidate(String structure) {
        boolean isJsonObj = JSONUtil.isJsonObj(structure);
        return Validate.builder().checked(isJsonObj).message(isJsonObj ? IsEnableEnum.YES.getDesc() : "复选框阈值预设检测不通过").build();
    }

    @Override
    public Validate valueValidate(String structure, String value) {
        JSONObject jsonObject = JSONUtil.parseObj(structure);
        boolean pass = JSONUtil.isJsonArray(value);
        if(pass){
            JSONArray objects = JSONUtil.parseArray(value);
            Optional<String> first = objects.stream().map(Object::toString).filter(checkKey ->
                    !jsonObject.containsKey(checkKey)).findFirst();
            pass = !first.isPresent();
        }
        return Validate.builder().checked(pass).message(pass ? IsEnableEnum.YES.getDesc():"复选框选项参数不匹配").build();
    }

    @Override
    public String previewValue(String structure, Object value) {
        String key = Objects.isNull(value)? StrUtil.EMPTY:String.valueOf(value);
        Validate validate = valueValidate(structure, key);
        if(Objects.nonNull(validate) && validate.getChecked()){
             JSONObject jsonObject = JSONUtil.parseObj(structure);
             JSONArray objects = JSONUtil.parseArray(value);
             return objects.stream().map(Object::toString).map(jsonObject::get).map(Object::toString)
                     .collect(Collectors.joining(StrUtil.COMMA));
        }
        return StrUtil.EMPTY;
    }

    @Override
    public Object resultValue(String value) {
        JSONArray objects = JSONUtil.parseArray(value);
        return objects.stream().toArray();
    }

    @Override
    public String resultValue(Object value) {
        return JSONUtil.toJsonStr(value);
    }
}
